package util;

import config.AppConfig;
import domain.constants.UserJwtConstants;
import internal.InternalResult;
import internal.UserJwt;
import io.jsonwebtoken.*;

import java.util.Date;
import java.util.Map;

public final class UserJwtHelper {

    public static InternalResult buildJwt(Map<String, Object> claims, long expSeconds, String securityKey) {
        if (claims == null) {
            return InternalResult.crateError("claims不允许为空", false);
        }
        if (expSeconds < 0) {
            return InternalResult.crateError("过期时间有误", false);
        }
        if (StringValidator.isBlank(securityKey)) {
            return InternalResult.crateError("securityKey不允许为空", false);
        }

        long now = System.currentTimeMillis();
        long exp = now + expSeconds * 1000;
        JwtBuilder jwtBuilder = Jwts.builder()
                //发行时间
                .setIssuedAt(new Date())
                //过期时间
                .setExpiration(new Date(exp))
                //签名
                .signWith(SignatureAlgorithm.HS256, securityKey)
                //添加额外的声明
                .addClaims(claims);
        //生成jwt
        String jwt = jwtBuilder.compact();
        return InternalResult.createSuccessResult(jwt);
    }

    public static InternalResult buildJwt(Map<String, Object> claims) {
        long expSeconds = AppConfig.JwtConfig.getExpDay() * 24 * 60 * 60;
        String jwtSecurityKey = AppConfig.JwtConfig.getJwtSecurityKey();
        return buildJwt(claims, expSeconds, jwtSecurityKey);
    }

    public static UserJwt ParseToken(String token, String securityKey) {
        try {
            Claims claims = Jwts.parser().setSigningKey(securityKey)
                    .parseClaimsJws(token).getBody();

            return new UserJwt(claims.get(UserJwtConstants.USER_ID_CLAIM_KEY).toString(),
                    claims.get(UserJwtConstants.USER_JWT_VERSION_CLAIM_KEY).toString(),
                    claims.getIssuedAt(),
                    claims.getExpiration());

        } catch (SignatureException signatureException) {
            return UserJwt.createFailJwt("验签失败,jwt失效");
        } catch (ExpiredJwtException expiredJwtException) {
            return UserJwt.createFailJwt("jwt过期");
        } catch (Exception e) {
            return UserJwt.createFailJwt("其他原因" + e);
        }
    }

    public static UserJwt ParseToken(String token) {
        String jwtSecurityKey = AppConfig.JwtConfig.getJwtSecurityKey();
        return ParseToken(token, jwtSecurityKey);
    }


}
